<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <h1>Proxy</h1>
    <button onclick="set()">set</button>
    <button onclick="get()">get</button>

    <div id="render">
      <h2></h2>
      <div class="info"></div>
      <ul class="list"></ul>
    </div>
    <script>
      let obj = {
        name: "henq",
        addr: {
          phone: "182",
          city: "西安",
          live: ["台球", "游泳", "象棋"],
        },
        users: [
          { name: "张三", age: 21 },
          { name: "li三", age: 21 },
          { name: "wang三", age: 21 },
        ],
      };
      const reactiveMap = new WeakMap();
      const handler = {
        get(target, key, receiver) {
          // console.log("get", target, key,);
          // return target[key];
          let res = Reflect.get(target, key, receiver);
          console.warn(res);

          if (typeof res === "object") {
            console.warn("res", target, key);
            if (reactiveMap.has(res)) {
              return reactiveMap.get(res);
            }
            return reactive(res);
          }
          return res;
        },
        set(target, key, value, receiver) {
          console.warn("set", target, key, value, receiver);
          return Reflect.set(target, key, value, receiver);
        },
      };
      const reactive = (state) => {
        if (typeof state !== "object") {
          return state;
        }
        if (reactiveMap.has(state)) {
          return reactiveMap[state];
        }
        const proxy = new Proxy(state, handler);
        reactiveMap.set(state, proxy);
        return proxy;
      };
      const state = reactive(obj);
      function get() {
        //    let item= state.users.pop();
        state.name = "hello!";
        console.warn("proxy", state);
        flush();
      }
      function set() {
        let item = state.addr.live.pop();
        console.warn("pop", item);
        flush();
      }
      function flush() {
        console.warn("state.name", state.name);
        let render = document.getElementById("render");
        render.querySelector("h2").innerHTML = state.name;
        render.querySelector(".info").innerHTML = `phone:${state.addr.phone}<br/>city:${state.addr.phone}<br/>live:${state.addr.live.join()}`
        render.querySelector(".list").innerHTML = state.users.map(u => {
            return `<li>${u.name}  --${u.age}岁</li>`
        }).join("")
        // render.innerHTML = JSON.stringify(state);
      }
      flush();
    </script>
  </body>
</html>
